import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Select, 
  DatePicker, 
  InputNumber, 
  Switch, 
  Button, 
  Space, 
  Divider, 
  Collapse,
  Tag,
  message
} from 'antd';
import { FilterOutlined, ClearOutlined, SaveOutlined } from '@ant-design/icons';
import { SearchFilters, Tag as TagType } from '../../../services/search/types';
import { ContentType } from '../../../types/document';
import { tagService } from '../../../services/search';
import { FilterProcessor } from '../../../services/search/filterProcessor';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Panel } = Collapse;

interface FilterPanelProps {
  filters: SearchFilters;
  onFiltersChange: (filters: SearchFilters) => void;
  onApply?: () => void;
  className?: string;
  compact?: boolean;
}

export const FilterPanel: React.FC<FilterPanelProps> = ({
  filters,
  onFiltersChange,
  onApply,
  className,
  compact = false
}) => {
  const [form] = Form.useForm();
  const [availableTags, setAvailableTags] = useState<TagType[]>([]);
  const [filterProcessor] = useState(() => new FilterProcessor());

  // 加载可用标签
  useEffect(() => {
    loadAvailableTags();
  }, []);

  // 同步表单值
  useEffect(() => {
    syncFormValues();
  }, [filters]);

  const loadAvailableTags = async () => {
    try {
      const tags = await tagService.getAllTags();
      setAvailableTags(tags);
    } catch (error) {
      console.error('[FilterPanel] 加载标签失败:', error);
    }
  };

  const syncFormValues = () => {
    const formValues: any = {
      contentType: filters.contentType || [],
      dateRange: filters.dateRange ? [
        dayjs(filters.dateRange.start),
        dayjs(filters.dateRange.end)
      ] : undefined,
      tags: filters.tags || [],
      minSize: filters.minSize,
      maxSize: filters.maxSize,
      hasAttachments: filters.hasAttachments
    };

    form.setFieldsValue(formValues);
  };

  // 处理表单值变化
  const handleValuesChange = (changedValues: any, allValues: any) => {
    const newFilters: SearchFilters = {};

    // 内容类型
    if (allValues.contentType && allValues.contentType.length > 0) {
      newFilters.contentType = allValues.contentType;
    }

    // 时间范围
    if (allValues.dateRange && allValues.dateRange.length === 2) {
      newFilters.dateRange = {
        start: allValues.dateRange[0].valueOf(),
        end: allValues.dateRange[1].valueOf()
      };
    }

    // 标签
    if (allValues.tags && allValues.tags.length > 0) {
      newFilters.tags = allValues.tags;
    }

    // 文档大小
    if (allValues.minSize !== undefined && allValues.minSize !== null) {
      newFilters.minSize = allValues.minSize;
    }
    if (allValues.maxSize !== undefined && allValues.maxSize !== null) {
      newFilters.maxSize = allValues.maxSize;
    }

    // 附件状态
    if (allValues.hasAttachments !== undefined) {
      newFilters.hasAttachments = allValues.hasAttachments;
    }

    // 验证筛选条件
    const validationError = filterProcessor.validateFilters(newFilters);
    if (validationError) {
      message.error(validationError);
      return;
    }

    onFiltersChange(newFilters);
  };

  // 清除所有筛选条件
  const handleClear = () => {
    form.resetFields();
    onFiltersChange({});
  };

  // 应用筛选
  const handleApply = () => {
    onApply?.();
  };

  // 获取内容类型选项
  const getContentTypeOptions = () => {
    return [
      { label: '文本文档', value: ContentType.TEXT_DOCUMENT },
      { label: '分镜脚本', value: ContentType.STORYBOARD },
      { label: '数据采集', value: ContentType.DATA_COLLECTION }
    ];
  };

  // 获取筛选条件描述
  const getFiltersDescription = () => {
    return filterProcessor.getFiltersDescription(filters);
  };

  // 检查是否有筛选条件
  const hasFilters = !FilterProcessor.isEmptyFilters(filters);

  if (compact) {
    return (
      <Card 
        size="small" 
        className={`filter-panel-compact ${className || ''}`}
        title={
          <Space>
            <FilterOutlined />
            <span>筛选</span>
            {hasFilters && <span className="filter-count">({Object.keys(filters).length})</span>}
          </Space>
        }
        extra={
          <Space>
            {hasFilters && (
              <Button 
                size="small" 
                icon={<ClearOutlined />} 
                onClick={handleClear}
                title="清除筛选"
              />
            )}
          </Space>
        }
      >
        <Collapse ghost>
          <Panel header="筛选条件" key="filters">
            {renderFilterForm()}
          </Panel>
        </Collapse>
      </Card>
    );
  }

  return (
    <Card 
      className={`filter-panel ${className || ''}`}
      title={
        <Space>
          <FilterOutlined />
          <span>高级筛选</span>
        </Space>
      }
      extra={
        <Space>
          <Button size="small" onClick={handleClear} icon={<ClearOutlined />}>
            清除
          </Button>
          {onApply && (
            <Button size="small" type="primary" onClick={handleApply}>
              应用
            </Button>
          )}
        </Space>
      }
    >
      {renderFilterForm()}
      
      {hasFilters && (
        <>
          <Divider />
          <div className="filter-summary">
            <span className="filter-summary-label">当前筛选:</span>
            <span className="filter-summary-text">{getFiltersDescription()}</span>
          </div>
        </>
      )}
    </Card>
  );

  function renderFilterForm() {
    return (
      <Form
        form={form}
        layout="vertical"
        size="small"
        onValuesChange={handleValuesChange}
      >
        {/* 内容类型筛选 */}
        <Form.Item 
          name="contentType" 
          label="内容类型"
        >
          <Select
            mode="multiple"
            placeholder="选择内容类型"
            options={getContentTypeOptions()}
            maxTagCount="responsive"
          />
        </Form.Item>

        {/* 时间范围筛选 */}
        <Form.Item 
          name="dateRange" 
          label="创建时间"
        >
          <RangePicker
            style={{ width: '100%' }}
            placeholder={['开始时间', '结束时间']}
            format="YYYY-MM-DD"
          />
        </Form.Item>

        {/* 标签筛选 */}
        <Form.Item 
          name="tags" 
          label="标签"
        >
          <Select
            mode="multiple"
            placeholder="选择标签"
            maxTagCount="responsive"
            optionRender={(option) => (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div 
                  style={{ 
                    width: 12, 
                    height: 12, 
                    borderRadius: '50%', 
                    backgroundColor: availableTags.find(t => t.id === option.value)?.color || '#ddd'
                  }} 
                />
                <span>{option.label}</span>
                <span style={{ marginLeft: 'auto', color: '#999', fontSize: '12px' }}>
                  {availableTags.find(t => t.id === option.value)?.usageCount || 0}
                </span>
              </div>
            )}
          >
            {availableTags.map(tag => (
              <Option key={tag.id} value={tag.id}>
                {tag.name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        {/* 文档大小筛选 */}
        <Form.Item label="文档大小（字符数）">
          <div className="size-range-inputs">
            <Form.Item 
              name="minSize" 
              style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
            >
              <InputNumber
                placeholder="最小值"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
            <span className="range-separator">至</span>
            <Form.Item 
              name="maxSize" 
              style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
            >
              <InputNumber
                placeholder="最大值"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </div>
        </Form.Item>

        {/* 附件状态筛选 */}
        <Form.Item 
          name="hasAttachments" 
          label="附件状态"
          valuePropName="checked"
        >
          <Switch 
            checkedChildren="有附件" 
            unCheckedChildren="无附件" 
          />
        </Form.Item>
      </Form>
    );
  }
};

const styles = `
  .filter-panel {
    border-radius: 8px;
  }

  .filter-panel-compact {
    border-radius: 6px;
  }

  .filter-count {
    color: #1890ff;
    font-weight: 500;
  }

  .size-range-inputs {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .range-separator {
    color: #999;
    font-size: 12px;
    margin: 0 4px;
  }

  .filter-summary {
    background-color: #f5f5f5;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 12px;
  }

  .filter-summary-label {
    color: #666;
    margin-right: 8px;
  }

  .filter-summary-text {
    color: #333;
  }
`;

// 注入样式
if (typeof document !== 'undefined') {
  const styleSheet = document.createElement('style');
  styleSheet.textContent = styles;
  document.head.appendChild(styleSheet);
}

export default FilterPanel;